package com.javabasic.algorithm.leetcode;

import java.util.HashSet;
import java.util.Objects;

/**
 * @author xiongmin
 * @version 0.0.1
 * @description Created by work on 2021/10/19 1:21 上午
 * @see
 */
public class DesignAddAndSearchWordsDataStructure {

}

class WordDictionary {

    private Word[] words;
    int len = 16;
    int index;
    double rate = 0.75;
    HashSet<Integer> hasKey;

    public WordDictionary() {
        words = new Word[len];
        index = 0;
        hasKey = new HashSet<>(16);
    }

    public void addWord(String word) {
        if (len*rate < index) {
            expendWord();
        }
        Word word1 = new Word(word);
        words[index++] = word1;
        hasKey.add(word1.getHashKey());
    }

    private void expendWord() {
        Word[] newWord = new Word[len*2];
        for (int i = 0; i < index; i++) {
            newWord[i] = words[i];
        }
        words = newWord;
    }

    public boolean search(String word) {
        Word word1 = new Word(word);
        if (hasKey.contains(word1.getHashKey()) || word.contains(".")) {
            for (int i = 0; i < index; i++) {
                if (words[i].isMatch(word)) {
                    return true;
                }
            }
        }
        return false;
    }
}
class Word {
    private String word;
    private int hashKey;

    public Word(String word) {
        this.word = word;
        if (null != word && !word.isEmpty()) {
            int len = this.word.length();
            this.hashKey = len + this.word.charAt(0) + this.word.charAt(len-1);
        }
    }

    public boolean isMatch(String matchStr) {
        if (Objects.equals(word,matchStr)) return true;
        int length = matchStr.length();
        if (this.word.length() == length) {
            System.out.println(this.word + " " + matchStr);
            for (int i = 0; i < length; i++) {
                if (matchStr.charAt(i) != '.' && this.word.charAt(i) != matchStr.charAt(i)) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public int getHashKey() {
        return hashKey;
    }

    public void setHashKey(int hashKey) {
        this.hashKey = hashKey;
    }
}